package com.goldman.oss.common.internal.processor.context;

import com.goldman.oss.common.platform.FileStorage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.concurrent.CopyOnWriteArrayList;


@Slf4j
public class ProcessorContext {
    public static CopyOnWriteArrayList<FileStorage> fileStorageList = new CopyOnWriteArrayList<>();

    public static void addFileStorage(FileStorage fileStorage) {
        log.info("添加对象存储平台到上下文{}", fileStorage.getBusinessCode());
        fileStorageList.add(fileStorage);
    }

    public static FileStorage getFileStorage(String businessCode) {
        if (StringUtils.isNotBlank(businessCode)) {
            for (FileStorage fileStorage : fileStorageList) {
                if (fileStorage.getBusinessCode().equalsIgnoreCase(businessCode)) {
                    return fileStorage;
                }
            }
            throw new RuntimeException("没有与指定businessCode匹配的对象存储平台");
        } else if (CollectionUtils.isEmpty(fileStorageList)) {
            throw new RuntimeException("没有启用的对象存储平台");
        } else if (fileStorageList.size() > 1) {
            throw new RuntimeException("启用了多个对象存储平台，但是没有指定businessCode");
        } else {
            return fileStorageList.get(0);
        }
    }


    public static CopyOnWriteArrayList<FileStorage> getAllFileStorages() {
        return fileStorageList;
    }

}
